<template>
  <div class="workorder-page">
    <!-- 简化的页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button
          type="primary"
          icon="el-icon-arrow-left"
          class="back-btn"
          @click="goBack"
          >
          返回
        </el-button>
        <h1 class="page-title">{{ isCreateMode ? '创建工单' : '工单处理' }}</h1>

        <!-- 状态显示标识 -->
        <div class="status-display">
          <span class="status-badge" :class="statusClass">
            {{ displayStatus }}
          </span>
        </div>
      </div>
      <div class="header-right">
        <el-button size="small" @click="saveDraft">保存草稿</el-button>
        <el-button size="small" @click="printOrder">打印</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="submitting"
          @click="submitOrder">
          {{ isCreateMode ? '创建工单' : '提交工单' }}
        </el-button>
      </div>
    </div>

    <!-- 简洁实用的内容布局 -->
    <div class="content-wrapper">
      <div class="content-container">

        <!-- 表单区域 -->
        <div class="form-sections">

          <!-- 基础信息 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">基础信息</h3>
              <div class="section-status" :class="{ 'complete': basicInfoComplete }">
                <i class="el-icon-check" v-if="basicInfoComplete"></i>
                <i class="el-icon-warning" v-else></i>
                <span>{{ basicInfoProgress.filled }}/{{ basicInfoProgress.total }} {{ basicInfoComplete ? '已完成' : '未完成' }}</span>
              </div>
            </div>
            <div class="section-content">
              <BasicInfoForm
                ref="basicForm"
                :form-data="workOrder"
                :fields="basicFields"
                :rules="formRules"
                :user-list="userList"
                :compact="true"
                class="form-component"
              />
            </div>
          </div>

          <!-- 异常信息 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">异常信息</h3>
              <div class="section-status" :class="{ 'complete': anomalyInfoComplete }">
                <i class="el-icon-check" v-if="anomalyInfoComplete"></i>
                <i class="el-icon-warning" v-else></i>
                <span>{{ anomalyInfoProgress.filled }}/{{ anomalyInfoProgress.total }} {{ anomalyInfoComplete ? '已完成' : '未完成' }}</span>
              </div>
            </div>
            <div class="section-content">
              <AnomalyInfoForm
                ref="anomalyForm"
                :form-data="workOrder"
                :rules="formRules"
                :anomaly-types="groupedAnomalyTypes"
                :compact="true"
                class="form-component"
              />
            </div>
          </div>

          <!-- 故障分析 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">故障分析</h3>
              <div class="section-status" :class="{ 'complete': faultAnalysisComplete }">
                <i class="el-icon-check" v-if="faultAnalysisComplete"></i>
                <i class="el-icon-warning" v-else></i>
                <span>{{ faultAnalysisProgress.filled }}/{{ faultAnalysisProgress.total }} {{ faultAnalysisComplete ? '已完成' : '未完成' }}</span>
              </div>
            </div>
            <div class="section-content">
              <FaultAnalysisForm
                ref="faultAnalysisForm"
                :form-data="workOrder"
                :compact="true"
                class="form-component"
              />
            </div>
          </div>

          <!-- 处理信息 - 仅在创建模式下隐藏 -->
          <div class="form-section" v-if="!isCreateMode">
            <div class="section-header">
              <h3 class="section-title">处理信息</h3>
              <div class="section-status" :class="{ 'complete': processingInfoComplete }">
                <i class="el-icon-check" v-if="processingInfoComplete"></i>
                <i class="el-icon-warning" v-else></i>
                <span>{{ processingInfoProgress.filled }}/{{ processingInfoProgress.total }} {{ processingInfoComplete ? '已完成' : '未完成' }}</span>
              </div>
            </div>
            <div class="section-content">
              <ProcessingInfoForm
                :form-data="workOrder"
                :date-picker-options="datePickerOptions"
                :user-list="userList"
                :compact="true"
                class="form-component"
              />
            </div>
          </div>

          <!-- 现场确认 - 仅在创建模式下隐藏 -->
          <div class="form-section" v-if="!isCreateMode">
            <div class="section-header">
              <h3 class="section-title">现场确认</h3>
              <div class="section-status" :class="{ 'complete': manualInputComplete }">
                <i class="el-icon-check" v-if="manualInputComplete"></i>
                <i class="el-icon-warning" v-else></i>
                <span>{{ manualInputProgress.filled }}/{{ manualInputProgress.total }} {{ manualInputComplete ? '已完成' : '未完成' }}</span>
              </div>
            </div>
            <div class="section-content">
              <ManualInputForm
                ref="manualInputForm"
                :form-data="workOrder"
                :compact="true"
                class="form-component"
              />
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
// Import components
import BasicInfoForm from './components/BasicInfoForm.vue';
import AnomalyInfoForm from './components/AnomalyInfoForm.vue';
import FaultAnalysisForm from './components/FaultAnalysisForm.vue';
import ManualInputForm from './components/ManualInputForm.vue';
import ProcessingInfoForm from './components/ProcessingInfoForm.vue';

// Import API functions
import { addOrder, updateOrder } from '@/api/fault/order';
import { addAnalysis } from '@/api/fault/analysis';
import { addProcess } from '@/api/fault/process';
import { listUser } from '@/api/system/user'; // 引入获取用户列表的接口


export default {
  name: 'WorkOrder',
  dicts: ['gelly_abnormal_type', 'gelly_fault_level', 'gelly_order_status'],
  components: {
    BasicInfoForm, //负责收集工单的基础信息
    AnomalyInfoForm, //负责收集工单的异常信息
    FaultAnalysisForm, //负责收集工单的故障信息
    ManualInputForm, //负责收集工单的输入信息
    ProcessingInfoForm //负责处理工单
  },
  data() {
    return {
      userList: [], // 新增：用户列表
      workOrder: {
        workOrderId: `WO-${new Date().getFullYear()}-${Date.now().toString().slice(-5)}`,
        equipmentName: '',
        equipmentType: '',
        equipmentModel: '', // 新增：设备型号
        installationLocation: '',
        workSection: '', // 新增：工段信息
        productionPart: '', // 新增：生产零件
        sensorId: '',
        sensorPosition: '', // 新增：传感器安装位置
        deviceInfo: '', // 新增：设备信息（格式：设备名称-传感器编号-安装位置）
        anomalyOccurrenceTime: '',
        anomalyDescription: '',
        anomalyType: '',
        affectedAxis: [],
        faultCause: '', // 新增：故障原因
        troubleshootingProcess: '', // 新增：排查思路
        troubleshootingTime: '', // 新增：排查时间
        troubleshootingEndTime: '', // 新增：排查结束时间
        repairStartTime: '', // 新增：维修开始时间
        repairEndTime: '', // 新增：维修结束时间
        replacedParts: '', // 新增：更换零件
        toolsUsed: '', // 新增：使用工具
        operationSteps: '', // 新增：操作步骤
        preventiveMeasures: '', // 新增：预防措施
        similarCases: '', // 新增：类似案例
        handler: '',
        handlerId: null, // 新增：处理人ID
        estimatedTime: '',
        solution: '',
        onSiteObservation: '',
        processingStatus: '待处理',
        acceptanceResult: '',
        closureReason: '',
        faultLevel: '',  // 新增：故障级别，默认为空，需要用户选择
        impactAssessment: '', // 新增：影响评估
        // 新增基础信息进度判定字段
        reporter: '',
        reporterId: null, // 新增：报告人ID
        occurredTime: '',
      },
      submitting: false,
      currentOrderId: null, // 存储创建的工单ID
      submitStep: 0, // 跟踪提交步骤：0-未开始，1-基础信息已提交，2-分析已提交，3-处理已提交

      datePickerOptions: {
        shortcuts: [
          { text: '今天', onClick(picker) { picker.$emit('pick', new Date()); } },
          { text: '明天', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 24); picker.$emit('pick', d); } },
          { text: '一周后', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 24 * 7); picker.$emit('pick', d); } }
        ]
      },
      formRules: {
        equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        anomalyDescription: [{ required: true, message: '请填写异常描述', trigger: 'blur' }],
        anomalyType: [{ required: true, message: '请选择异常类型', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchUserList(); // 新增：获取用户列表
    const queryParams = this.$route.query;

    // 检查是否从工单列表跳转过来（处理模式）
    if (queryParams.mode === 'process' && queryParams.id) {
      this.loadWorkOrderForProcessing(queryParams);
    } else {
      // 新增：处理从AI问询或监控页面跳转过来的情况
      this.loadFromMonitoringPage(queryParams);
    }
  },
  mounted() {
    // 确保自动填入的数据能触发响应式更新
    this.$nextTick(() => {
      this.$forceUpdate();
    });
  },
  computed: {
    // 判断是否为创建模式
    isCreateMode() {
      return this.$route.query.mode === 'create';
    },
    displayStatus() {
      const statusMap = {
        '待处理': '未处理',
        '处理中': '处理中',
        '已完成': '已完成'
      };
      return statusMap[this.workOrder.processingStatus] || '未处理';
    },
    statusClass() {
      const classMap = {
        '待处理': 'status-pending',
        '处理中': 'status-processing',
        '已完成': 'status-completed'
      };
      return classMap[this.workOrder.processingStatus] || 'status-pending';
    },
    currentStep() {
      const statusMap = {
        '待处理': 0,
        '处理中': 1,
        '已完成': 2
      };
      return statusMap[this.workOrder.processingStatus] || 0;
    },
    // 基础信息模块完整性 - 考虑自动填入的数据
    basicInfoComplete() {
      // 只要填写了设备、报告人、发生时间、故障等级即可
      const hasEquipment = !!(this.workOrder.equipmentName || this.workOrder.equipmentCode);
      const hasReporter = !!this.workOrder.reporter;
      const hasTime = !!this.workOrder.occurredTime;
      // 修改：只有当用户选择了故障等级时才视为已填写（不能为空字符串）
      const hasLevel = this.workOrder.faultLevel !== undefined &&
                       this.workOrder.faultLevel !== null &&
                       this.workOrder.faultLevel !== '';
  
      return hasEquipment && hasReporter && hasTime && hasLevel;
    },
    // 异常信息模块完整性 - 考虑自动填入的数据
    anomalyInfoComplete() {
      // 检查所有必要字段是否已填写（不管是自动填入还是手动填写）
      const hasDescription = !!this.workOrder.anomalyDescription;
      const hasType = !!this.workOrder.anomalyType;
      const hasAxis = !!(this.workOrder.affectedAxis && this.workOrder.affectedAxis.length > 0);

      return hasDescription && hasType && hasAxis;
    },
    // 故障分析模块完整性
    faultAnalysisComplete() {
      return !!(this.workOrder.faultCause &&
                this.workOrder.solution &&
                this.workOrder.preventiveMeasures &&
                this.workOrder.impactAssessment);
    },
    // 处理信息模块完整性
    processingInfoComplete() {
      return !!(this.workOrder.handler &&
                this.workOrder.estimatedTime &&
                this.workOrder.solution &&
                this.workOrder.onSiteObservation);
    },
    // 现场确认模块完整性
    manualInputComplete() {
      return !!(this.workOrder.productionPart &&
                this.workOrder.onSiteObservation &&
                this.workOrder.acceptanceResult);
    },
    workflowSteps() {
      return [
        {
          key: 'info',
          title: '基础信息收集',
          description: '🤖 系统自动获取设备信息',
          icon: 'el-icon-document',
          automation: 'auto'
        },
        {
          key: 'analysis',
          title: 'AI智能分析',
          description: '🧠 AI分析异常并生成故障诊断',
          icon: 'el-icon-cpu',
          automation: 'ai'
        },
        {
          key: 'manual',
          title: '现场确认处理',
          description: '👤 人工确认并执行维修方案',
          icon: 'el-icon-user',
          automation: 'manual'
        },
        {
          key: 'complete',
          title: '验收完成',
          description: '✅ 专业验收并生成知识库',
          icon: 'el-icon-check',
          automation: 'manual'
        }
      ]
    },
    groupedAnomalyTypes() {
      // 使用字典数据
      if (!this.dict.type.gelly_abnormal_type) {
        return [];
      }

      // 将字典数据转换为分组格式
      return [
        {
          label: '异常类型',
          options: this.dict.type.gelly_abnormal_type.map(item => ({
            label: item.label,
            value: item.value // 保持与系统字典一致，使用原始值
          }))
        }
      ];
    },
    basicFields() {
      // TODO: 这些字段配置应该从系统配置或API获取
      return [
        {
          prop: 'workOrderId',
          label: '工单编号',
          comp: 'el-input',
          bind: { readonly: true }
        },
        {
          prop: 'equipmentName',
          label: '设备名称',
          comp: 'el-input',
          required: true,
          bind: { placeholder: '设备名称', clearable: true }
        },
        {
          prop: 'equipmentType',
          label: '设备类型',
          comp: 'el-input',
          bind: { placeholder: '设备类型', clearable: true }
        },
        {
          prop: 'equipmentModel',
          label: '设备型号',
          comp: 'el-input',
          bind: { placeholder: '设备型号', clearable: true }
        },
        {
          prop: 'installationLocation',
          label: '安装位置',
          comp: 'el-input',
          bind: { placeholder: '安装位置', clearable: true }
        },
        {
          prop: 'workSection',
          label: '工段',
          comp: 'el-input',
          bind: { placeholder: '工段', clearable: true }
        },
        {
          prop: 'productionPart',
          label: '更换零件',
          comp: 'el-input',
          bind: { placeholder: '更换零件', clearable: true }
        },
        {
          prop: 'sensorId',
          label: '传感器编号',
          comp: 'el-input',
          bind: { placeholder: '传感器编号', clearable: true }
        },
        {
          prop: 'anomalyOccurrenceTime',
          label: '异常发生时间',
          comp: 'el-date-picker',
          required: true,
          bind: {
            type: 'datetime',
            placeholder: '选择时间',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          }
        }
      ]
    },
    basicInfoProgress() {
      let filled = 0, total = 4;
      if (this.workOrder.equipmentName || this.workOrder.equipmentCode) filled++;
      if (this.workOrder.reporter) filled++;
      if (this.workOrder.occurredTime) filled++;
      if (this.workOrder.faultLevel !== undefined && this.workOrder.faultLevel !== null && this.workOrder.faultLevel !== '') filled++;
      return { filled, total };
    },
    anomalyInfoProgress() {
      let filled = 0, total = 3;
      if (this.workOrder.anomalyDescription) filled++;
      if (this.workOrder.anomalyType) filled++;
      if (this.workOrder.affectedAxis && this.workOrder.affectedAxis.length > 0) filled++;
      return { filled, total };
    },
    faultAnalysisProgress() {
      let filled = 0, total = 4;
      if (this.workOrder.faultCause) filled++;
      if (this.workOrder.solution) filled++;
      if (this.workOrder.preventiveMeasures) filled++;
      if (this.workOrder.impactAssessment) filled++;
      return { filled, total };
    },
    processingInfoProgress() {
      let filled = 0, total = 4;
      if (this.workOrder.handler) filled++;
      if (this.workOrder.estimatedTime) filled++;
      if (this.workOrder.solution) filled++;
      if (this.workOrder.onSiteObservation) filled++;
      return { filled, total };
    },
    manualInputProgress() {
      let filled = 0, total = 3;
      if (this.workOrder.productionPart) filled++;
      if (this.workOrder.onSiteObservation) filled++;
      if (this.workOrder.acceptanceResult) filled++;
      return { filled, total };
    }
  },
  methods: {
    // 格式化当前时间为本地时间字符串
    formatCurrentTime(date = new Date()) {
      // 确保使用本地时间（中国时区）
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 新增：从监控或AI问询页面加载数据并自动填充
    loadFromMonitoringPage(queryParams) {
      if (!queryParams) return;

      console.log('📋 工单页面接收到的查询参数:', queryParams);
      console.log('🔍 关键参数检查:', {
        faultLevel: queryParams.faultLevel,
        anomalyType: queryParams.anomalyType,
        affectedAxis: queryParams.affectedAxis,
        axis: queryParams.axis
      });

      // 生成当前本地时间（确保使用中国时区）
      const now = new Date();
      const formattedTime = this.formatCurrentTime(now);
      console.log('🕐 当前时间生成:', formattedTime, '原始时间对象:', now);

      // 设备信息自动填充（使用传入的deviceInfo或构建）
      if (queryParams.deviceInfo) {
        this.workOrder.deviceInfo = queryParams.deviceInfo;
        // 解析设备信息以填充其他字段
        const parts = queryParams.deviceInfo.split('-');
        if (parts.length >= 1) this.workOrder.equipmentName = parts[0];
        if (parts.length >= 2) this.workOrder.sensorId = parts[1];
        if (parts.length >= 3) this.workOrder.sensorPosition = parts[2];
      } else {
        // 如果没有deviceInfo，使用原有逻辑
        this.workOrder.equipmentName = queryParams.latheName || queryParams.equipmentName || '';
        this.workOrder.sensorId = queryParams.sensorId || '';
        this.workOrder.sensorPosition = queryParams.axis || '';
        // 构建设备信息
        this.workOrder.deviceInfo = `${this.workOrder.equipmentName}-${this.workOrder.sensorId}-${this.workOrder.sensorPosition}`;
      }

      this.workOrder.equipmentType = queryParams.equipmentType || '数控机床';
      this.workOrder.equipmentModel = queryParams.equipmentModel || '';
      this.workOrder.installationLocation = queryParams.installationLocation || '';
      this.workOrder.workSection = queryParams.workSection || '';

      // 故障等级自动映射（AI输出的数字值：0=紧急，1=重要，2=一般，3=轻微）
      console.log('🔍 故障等级参数检查:', queryParams.faultLevel, typeof queryParams.faultLevel);
      if (queryParams.faultLevel !== undefined && queryParams.faultLevel !== null && queryParams.faultLevel !== '') {
        const faultLevel = Number(queryParams.faultLevel);
        if (faultLevel >= 0 && faultLevel <= 3) {
          this.workOrder.faultLevel = faultLevel;

          // 获取故障等级的文字描述
          const faultLevelDict = this.dict.type.gelly_fault_level || [];
          const faultLevelLabel = faultLevelDict.find(item => Number(item.value) === faultLevel)?.label || '';

          console.log('✅ 工单页面设置故障等级:', this.workOrder.faultLevel, '文字描述:', faultLevelLabel);
        } else {
          console.log('❌ 故障等级超出范围:', faultLevel);
        }
      } else {
        console.log('❌ 故障等级参数为空或未定义');
      }

      // 异常类型自动映射（AI输出的数字值：0-9）
      console.log('🔍 异常类型参数检查:', queryParams.anomalyType, typeof queryParams.anomalyType);
      if (queryParams.anomalyType !== undefined && queryParams.anomalyType !== null && queryParams.anomalyType !== '') {
        const anomalyType = Number(queryParams.anomalyType);
        if (anomalyType >= 0 && anomalyType <= 9) {
          this.workOrder.anomalyType = anomalyType;

          // 获取异常类型的文字描述
          const anomalyTypeDict = this.dict.type.gelly_abnormal_type || [];
          const anomalyTypeLabel = anomalyTypeDict.find(item => Number(item.value) === anomalyType)?.label || '';

          console.log('✅ 工单页面设置异常类型:', this.workOrder.anomalyType, '文字描述:', anomalyTypeLabel);
          console.log('🔍 异常类型字典数据:', anomalyTypeDict.map(item => ({ value: item.value, type: typeof item.value, label: item.label })));
        } else {
          console.log('❌ 异常类型超出范围:', anomalyType);
        }
      } else {
        console.log('❌ 异常类型参数为空或未定义');
      }

      // 时间信息
      this.workOrder.occurredTime = queryParams.occurredTime || formattedTime;
      this.workOrder.anomalyOccurrenceTime = queryParams.anomalyOccurrenceTime || formattedTime;

      console.log('🕐 时间设置结果:', {
        传入的occurredTime: queryParams.occurredTime,
        传入的anomalyOccurrenceTime: queryParams.anomalyOccurrenceTime,
        生成的formattedTime: formattedTime,
        最终occurredTime: this.workOrder.occurredTime,
        最终anomalyOccurrenceTime: this.workOrder.anomalyOccurrenceTime
      });

      // 异常信息
      this.workOrder.anomalyDescription = queryParams.anomalyDescription || '';

      // 受影响轴向处理 - 详细调试
      console.log('🔍 轴向参数详细分析:');
      console.log('  - queryParams.affectedAxis:', queryParams.affectedAxis, typeof queryParams.affectedAxis);
      console.log('  - queryParams.axis:', queryParams.axis, typeof queryParams.axis);

      if (queryParams.affectedAxis) {
        // 如果是字符串，尝试解析为数组
        if (typeof queryParams.affectedAxis === 'string') {
          try {
            this.workOrder.affectedAxis = JSON.parse(queryParams.affectedAxis);
            console.log('✅ 解析字符串为数组:', this.workOrder.affectedAxis);
          } catch (e) {
            // 如果解析失败，按逗号分割
            this.workOrder.affectedAxis = queryParams.affectedAxis.split(',').map(s => s.trim());
            console.log('✅ 按逗号分割字符串:', this.workOrder.affectedAxis);
          }
        } else if (Array.isArray(queryParams.affectedAxis)) {
          this.workOrder.affectedAxis = queryParams.affectedAxis;
          console.log('✅ 直接使用数组:', this.workOrder.affectedAxis);
        } else {
          this.workOrder.affectedAxis = [queryParams.affectedAxis];
          console.log('✅ 转换为数组:', this.workOrder.affectedAxis);
        }
      } else if (queryParams.axis) {
        this.workOrder.affectedAxis = [queryParams.axis];
        console.log('✅ 使用备用axis参数:', this.workOrder.affectedAxis);
      } else {
        this.workOrder.affectedAxis = [];
        console.log('❌ 没有轴向参数');
      }

      console.log('✅ 最终设置的受影响轴向:', this.workOrder.affectedAxis);

      // 故障分析信息
      this.workOrder.faultCause = queryParams.faultCause || '';
      this.workOrder.solution = queryParams.solution || '';
      this.workOrder.troubleshootingProcess = queryParams.troubleshootingProcess || '';
      this.workOrder.preventiveMeasures = queryParams.preventiveMeasures || '';
      this.workOrder.similarCases = queryParams.similarCases || '';
      this.workOrder.impactAssessment = queryParams.impactAssessment || '';

      // 处理信息（如果有的话）
      this.workOrder.handler = queryParams.handler || '';
      this.workOrder.handlerId = queryParams.handlerId || null;
      this.workOrder.estimatedTime = queryParams.estimatedTime || '';
      this.workOrder.onSiteObservation = queryParams.onSiteObservation || '';
      this.workOrder.productionPart = queryParams.productionPart || '';
      this.workOrder.replacedParts = queryParams.replacedParts || '';
      this.workOrder.toolsUsed = queryParams.toolsUsed || '';
      this.workOrder.operationSteps = queryParams.operationSteps || '';

      // 报告人信息
      this.workOrder.reporter = queryParams.reporter || this.$store.getters.name || '系统';
      this.workOrder.reporterId = queryParams.reporterId || this.$store.getters.id || null;

      console.log('🔍 用户信息设置:', {
        传入的reporter: queryParams.reporter,
        传入的reporterId: queryParams.reporterId,
        store中的name: this.$store.getters.name,
        store中的id: this.$store.getters.id,
        最终reporter: this.workOrder.reporter,
        最终reporterId: this.workOrder.reporterId
      });

      console.log('自动填充完成，工单数据:', this.workOrder);
    },

    async fetchUserList() {
      try {
        const response = await listUser({ pageNum: 1, pageSize: 9999 }); // 传递分页参数获取所有用户
        if (response.code === 200) {
          this.userList = response.rows.map(user => ({
            label: user.userName, // 使用用户名作为显示
            value: user.userId // 使用userId作为ID
          }));
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
      }
    },
    formatDate(date) {
      if (!date) return new Date().toLocaleDateString();
      return new Date(date).toLocaleDateString();
    },

    // 格式化日期时间为API所需的格式
    formatDateTime(dateTime) {
      if (!dateTime) return null;

      let date;

      // 如果是字符串，尝试解析
      if (typeof dateTime === 'string') {
        date = new Date(dateTime);
        if (isNaN(date.getTime())) {
          return null;
        }
      }
      // 如果是Date对象
      else if (dateTime instanceof Date) {
        date = dateTime;
      }
      else {
        return null;
      }

      // 使用本地时间格式化（而不是UTC时间）
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      console.log('🕐 提交时间格式化:', { 原始时间: dateTime, 格式化后: formattedTime });

      return formattedTime;
    },

    // 验证必填字段
    validateOrderData(orderData) {
      const requiredFields = [
        { field: 'deviceInfo', name: '设备信息' },
        { field: 'abnormalDescription', name: '异常描述' },
        { field: 'abnormalType', name: '异常类型' }
      ];

      for (const { field, name } of requiredFields) {
        const value = orderData[field];
        // 修正验证逻辑，确保 0 被视为有效值
        if (value === undefined || value === null || value.toString().trim() === '') {
          throw new Error(`${name}不能为空`);
        }
      }
      
      return true;
    },

    // 创建模式的提交逻辑
    async submitCreateModeOrder() {
      // 验证基础信息、异常信息和故障分析
      await this.$refs.basicForm.validate();
      await this.$refs.anomalyForm.validate();
      await this.$refs.faultAnalysisForm.validate();

      // 第一步：提交基础信息和异常信息
      const orderData = {
        faultLevel: this.workOrder.faultLevel !== '' ? Number(this.workOrder.faultLevel) : null,
        deviceInfo: this.workOrder.deviceInfo || `${this.workOrder.equipmentName}-${this.workOrder.sensorId || ''}-${this.workOrder.sensorPosition || ''}`,
        reporterId: this.workOrder.reporterId,
        occurrenceTime: this.formatDateTime(this.workOrder.occurredTime),
        abnormalType: Number(this.workOrder.anomalyType),
        abnormalDescription: this.workOrder.anomalyDescription,
        affectedAxes: Array.isArray(this.workOrder.affectedAxis) ? this.workOrder.affectedAxis.join(',') : ''
      };

      // 验证数据
      this.validateOrderData(orderData);
      console.log("📤 提交工单数据:", orderData);
      console.log("🕐 提交时间详情:", {
        原始occurredTime: this.workOrder.occurredTime,
        格式化后occurrenceTime: orderData.occurrenceTime
      });
      // 提交基础信息和异常信息
      const orderResponse = await addOrder(orderData);
      console.log('addOrder 返回数据:', orderResponse);

      if (orderResponse.code !== 200) {
        throw new Error(orderResponse.msg || '基础信息提交失败');
      }

      // 检查返回数据结构并获取orderId
      console.log('orderResponse.data:', orderResponse.data);
      this.currentOrderId = orderResponse.data; // data 直接就是 orderId
      console.log('获取到的 currentOrderId:', this.currentOrderId);

      if (!this.currentOrderId) {
        throw new Error('未能获取到工单ID，请检查后端返回数据');
      }

      this.$message.success('基础信息提交成功');

      // 第二步：提交故障分析信息（复用 submitAnalysis 方法）
      await this.submitAnalysis();

      // 第三步：更新工单状态为"待处理"
      const updateData = {
        id: this.currentOrderId,
        orderStatus: 0 // 待处理状态
      };

      const updateResponse = await updateOrder(updateData);
      if (updateResponse.code !== 200) {
        throw new Error(updateResponse.msg || '工单状态更新失败');
      }

      this.$message.success('工单创建成功！');

      // 跳转回工单列表页
      setTimeout(() => {
        this.$router.push('/gelly/order');
      }, 1000);
    },

    // 提交故障分析信息
    async submitAnalysis() {
      if (!this.currentOrderId) {
        throw new Error('工单ID不存在，请先提交基础信息');
      }

      const analysisData = {
        orderId: this.currentOrderId,
        faultDescription: this.workOrder.anomalyDescription || '',
        faultCause: this.workOrder.faultCause || '',
        solution: this.workOrder.solution || '',
        preventiveMeasures: this.workOrder.preventiveMeasures || '',
        analystId: this.$store.getters.userId || 1
      };

      // 验证必填字段
      if (!analysisData.faultCause) {
        throw new Error('故障原因不能为空');
      }
      if (!analysisData.solution) {
        throw new Error('解决方案不能为空');
      }

      console.log('故障分析数据准备完成:', analysisData);
      console.log('当前 orderId:', this.currentOrderId);

      const response = await addAnalysis(analysisData);
      console.log('addAnalysis 返回数据:', response);

      if (response.code === 200) {
        this.submitStep = 2;
        this.$message.success('故障分析提交成功');
      } else {
        throw new Error(response.msg || '故障分析提交失败');
      }
    },

    // 提交处理过程信息
    async submitProcess() {
      if (!this.currentOrderId) {
        throw new Error('工单ID不存在，请先提交基础信息');
      }

      const processData = {
        orderId: this.currentOrderId,
        handlerId: this.$store.getters.userId || 1, // 使用当前登录用户ID
        handlingScheme: this.workOrder.solution || '',
        estimatedCompletionTime: this.formatDateTime(this.workOrder.estimatedTime),
        handlingNotes: this.workOrder.onSiteObservation || '',
        producedParts: this.workOrder.replacedParts || '',
        acceptanceResult: this.workOrder.acceptanceResult === '通过' ? 1 : (this.workOrder.acceptanceResult === '不通过' ? 2 : 0)
      };

      // 验证必填字段
      if (!processData.handlingScheme) {
        throw new Error('处理方案不能为空');
      }
      if (!processData.estimatedCompletionTime) {
        throw new Error('预计完成时间不能为空');
      }

      const response = await addProcess(processData);
      if (response.code === 200) {
        this.submitStep = 3;
        this.$message.success('处理信息提交成功');
      } else {
        throw new Error(response.msg || '处理信息提交失败');
      }
    },

    saveDraft() {
      this.$message({ message: '草稿已保存', type: 'success' });
    },

  
    async submitOrder() {
      this.submitting = true;
      try {
        // 创建模式：只提交前三个模块
        if (this.isCreateMode) {
          await this.submitCreateModeOrder();
          return;
        }

        // 原有的处理模式逻辑
        // 第一步：验证并提交基础信息和异常信息
        if (this.submitStep === 0) {
          await this.$refs.basicForm.validate();
          await this.$refs.anomalyForm.validate();

          // 准备基础信息和异常信息数据
          const orderData = {
            faultLevel: this.workOrder.faultLevel !== '' ? Number(this.workOrder.faultLevel) : null,
            deviceInfo: this.workOrder.deviceInfo || `${this.workOrder.equipmentName}-${this.workOrder.sensorId || ''}-${this.workOrder.sensorPosition || ''}`,
            reporterId: this.workOrder.reporterId,
            occurrenceTime: this.formatDateTime(this.workOrder.occurredTime),
            abnormalType: Number(this.workOrder.anomalyType),
            abnormalDescription: this.workOrder.anomalyDescription,
            affectedAxes: Array.isArray(this.workOrder.affectedAxis) ? this.workOrder.affectedAxis.join(',') : ''
          };
          console.log("📤 批量提交工单数据:", orderData);
          console.log("🕐 批量提交时间详情:", {
            原始occurredTime: this.workOrder.occurredTime,
            格式化后occurrenceTime: orderData.occurrenceTime
          });
          // 验证数据
          this.validateOrderData(orderData);

          // 提交基础信息和异常信息
          const response = await addOrder(orderData);
          if (response.code === 200) {
            this.currentOrderId = response.data.id;
            this.submitStep = 1;
            this.$message.success('基础信息提交成功');

            // 如果有故障分析信息，继续提交
            if (this.workOrder.faultCause && this.workOrder.solution) {
              await this.submitAnalysis();
            }
          } else {
            throw new Error(response.msg || '提交失败');
          }
        }
        // 如果已经有工单ID，直接提交分析信息
        else if (this.submitStep === 1) {
          await this.submitAnalysis();
        }
        // 如果分析信息已提交，提交处理信息
        else if (this.submitStep === 2) {
          await this.submitProcess();
        }

        // 如果工单状态为已完成，询问是否生成知识库条目
        if (this.workOrder.processingStatus === '已完成' && this.submitStep === 3) {
          this.$confirm('工单已完成，是否将此次维修记录添加到知识库？', '生成知识库条目', {
            confirmButtonText: '生成',
            cancelButtonText: '跳过',
            type: 'info'
          }).then(() => {
            this.generateKnowledgeBase();
          }).catch(() => {
            this.$message({ type: 'info', message: '已跳过知识库生成' });
          });

          // 全部提交完成，返回列表页
          setTimeout(() => {
            this.$router.back();
          }, 500);
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error(error.message || '请完善必填信息');
      } finally {
        // 无论成功或失败，最终都重置按钮状态
        if (!(this.workOrder.processingStatus === '已完成' && this.submitStep === 3)) {
          this.submitting = false;
        }
      }
    },
    generateKnowledgeBase() {
      // 生成知识库条目的Markdown格式
      const knowledgeEntry = this.formatToKnowledgeBase(this.workOrder);

      // 这里可以调用API保存到知识库，或者打开编辑对话框
      this.$alert(knowledgeEntry, '知识库条目预览', {
        confirmButtonText: '保存到知识库',
        customClass: 'knowledge-preview-dialog',
        dangerouslyUseHTMLString: false
      }).then(() => {
        // 调用API保存知识库条目
        this.saveToKnowledgeBase(knowledgeEntry);
      });
    },
    formatToKnowledgeBase(workOrder) {
      const deviceInfo = `${workOrder.equipmentName}（${workOrder.equipmentType}，型号：${workOrder.equipmentModel || '未填写'}）`;

      return `设备号：${workOrder.workOrderId}（${deviceInfo}）

| 维修单号 | ${workOrder.workOrderId}（唯一标识） |
| 设备名称 | ${workOrder.equipmentName} |
| 设备位置 | ${workOrder.installationLocation || '未填写'} |
| 工段 | ${workOrder.workSection || '未填写'} |
| 更换零件 | ${workOrder.productionPart || '未填写'} |
| 异常发生时间 | ${workOrder.anomalyOccurrenceTime} |
| 异常现象 | ${workOrder.anomalyDescription} |
| 故障原因 | ${workOrder.faultCause || '未填写'} |
| 排查时间 | ${workOrder.troubleshootingTime || '未填写'} - ${workOrder.troubleshootingEndTime || '未填写'} |
| 排查思路 | ${workOrder.troubleshootingProcess || '未填写'} |
| 维修时间 | ${workOrder.repairStartTime || '未填写'} - ${workOrder.repairEndTime || '未填写'} |
| 维修方式 | - 更换零件：${workOrder.replacedParts || '未填写'}；- 使用工具：${workOrder.toolsUsed || '未填写'}；- 操作步骤：${workOrder.operationSteps || '未填写'} |
| 类似案例 | ${workOrder.similarCases || '未填写'} |
| 预防措施 | ${workOrder.preventiveMeasures || '未填写'} |`;
    },
    saveToKnowledgeBase(knowledgeEntry) {
      // 这里调用API保存知识库条目
      console.log('保存知识库条目:', knowledgeEntry);
      this.$message({ message: '知识库条目已保存', type: 'success' });
    },
    printOrder() {
      window.print();
    },
    goBack() {
      this.$router.back();
    },

    // 流程锚定：点击步骤滚动到对应模块
    scrollToModule(stepKey, stepIndex) {
      this.currentStep = stepIndex;

      const moduleMap = {
        'info': 'module-info',
        'analysis': 'module-analysis',
        'manual': 'module-manual-detail',
        'complete': 'module-complete'
      };

      const moduleId = moduleMap[stepKey];
      if (moduleId) {
        const element = document.getElementById(moduleId);
        if (element) {
          element.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
            inline: 'nearest'
          });
        }
      }
    },

  }
}
</script>

<style scoped>
.workorder-page {
  min-height: 100vh;
  background: #fafbfc;
  position: relative;
  overflow-x: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

/* 现代简洁的页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(8px);
  border-bottom: 1px solid #f1f5f9;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  letter-spacing: -0.01em;
}

.status-display {
  margin-left: 20px;
}

.status-badge {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  letter-spacing: 0.02em;
}

.status-badge.status-pending {
  background: #fef3c7;
  color: #92400e;
}

.status-badge.status-processing {
  background: #dbeafe;
  color: #1e40af;
}

.status-badge.status-completed {
  background: #d1fae5;
  color: #065f46;
}

.header-right {
  display: flex;
  gap: 8px;
}

.header-right .el-button {
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  padding: 6px 12px;
  border: 1px solid #e5e7eb;
  background: white;
  color: #374151;
}

.header-right .el-button:hover {
  border-color: #d1d5db;
  background: #f9fafb;
}

.header-right .el-button--primary {
  background: #3b82f6;
  border-color: #3b82f6;
  color: white;
}

.header-right .el-button--primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}



/* 现代简洁的布局样式 */
.content-wrapper {
  padding: 20px;
  min-height: calc(100vh - 80px);
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
}

/* 表单区域 */
.form-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: none;
}

.section-header {
  padding: 16px 24px 12px;
  border-bottom: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  letter-spacing: -0.01em;
}

/* 模块完整性状态指示器 */
.section-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.section-status:not(.complete) {
  background: #fef3cd;
  color: #92400e;
  border: 1px solid #fbbf24;
}

.section-status.complete {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #10b981;
}

.section-status i {
  font-size: 14px;
}

.section-content {
  padding: 0 24px 24px;
}

.form-component {
  width: 100%;
}

/* 现代表单组件样式 */
.form-component .el-form-item {
  margin-bottom: 18px;
}

.form-component .el-form-item__label {
  color: #374151;
  font-weight: 500;
  font-size: 14px;
  line-height: 1.4;
  padding-bottom: 6px;
}

.form-component .el-input__inner,
.form-component .el-textarea__inner {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px 14px;
  font-size: 14px;
  transition: all 0.15s ease;
  background: #ffffff;
  line-height: 1.4;
}

.form-component .el-input__inner:hover,
.form-component .el-textarea__inner:hover {
  border-color: #d1d5db;
}

.form-component .el-input__inner:focus,
.form-component .el-textarea__inner:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.08);
  outline: none;
}

.form-component .el-input__inner::placeholder,
.form-component .el-textarea__inner::placeholder {
  color: #9ca3af;
  font-size: 14px;
}

.form-component .el-select .el-input__inner {
  cursor: pointer;
}

.form-component .el-date-editor .el-input__inner {
  cursor: pointer;
}

/* 表单验证错误样式 */
.form-component .el-form-item.is-error .el-input__inner,
.form-component .el-form-item.is-error .el-textarea__inner {
  border-color: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.08);
}

.form-component .el-form-item__error {
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 400;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .content-wrapper {
    padding: 12px;
  }

  .form-sections {
    gap: 12px;
  }

  .section-header {
    padding: 12px 16px 8px;
  }

  .section-content {
    padding: 0 16px 16px;
  }

  .page-header {
    padding: 10px 12px;
  }

  .header-left {
    gap: 12px;
  }

  .page-title {
    font-size: 16px;
  }

  .status-display {
    margin-left: 12px;
  }

  .header-right {
    gap: 6px;
  }

  .header-right .el-button {
    padding: 5px 8px;
    font-size: 13px;
  }
}

/* 简洁的打印样式 */
@media print {
  .workorder-page {
    background: white !important;
  }

  .page-header {
    display: none !important;
  }

  .content-wrapper {
    padding: 20px !important;
  }

  .form-section {
    page-break-inside: avoid;
    box-shadow: none !important;
  }
}




/* 知识库预览对话框样式 */
.workorder-page >>> .knowledge-preview-dialog {
  width: 80%;
  max-width: 800px;
}

.workorder-page >>> .knowledge-preview-dialog .el-message-box__content {
  max-height: 500px;
  overflow-y: auto;
  white-space: pre-wrap;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}
</style>
